package com.itxiaoxiong.chat.socket;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itxiaoxiong.chat.mapper.SocketMapMapper;
import com.itxiaoxiong.chat.pojo.ChatMessage;
import com.itxiaoxiong.chat.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

@Slf4j
@RestController
@CrossOrigin(origins = "*")
public class ChatController {
    private final ProxyServerManager proxyServerManager;
    private final HashMap<String, BlockingQueue<String>> userQueues = new HashMap<>();

    public ChatController(ProxyServerManager proxyServerManager) {
        this.proxyServerManager = proxyServerManager;
    }
    @Autowired
    private SocketMapMapper socketMapMapper;
    /*
        用于建立一个用户对应一个代理服务器
     */
    @PostMapping("/connect")
    public Result connect(@RequestBody String userId) {
        try {
            proxyServerManager.getOrCreateProxyServer(userId,userQueues);
            System.out.println("User " + userId + " 连接到代理服务器.");
            return Result.success();
        } catch (Exception e) {
            System.out.println("失败 " + userId + ": " + e.getMessage());
            return Result.error(userId);
        }
    }

    /*
    查询在线用户而已
     */
    @PostMapping("/sendMessage")
    public void sendMessage(@RequestBody String message) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode rootNode = objectMapper.readTree(message);
        message = rootNode.get("message").asText();
        if (socketMapMapper.getSocketByKey(message).size() == 0) {
            socketMapMapper.addSocket(message);
        }
    }


    @GetMapping("/poll")
    public ResponseEntity<String> poll(@RequestParam String id) {
        BlockingQueue<String> queue;
        if (!userQueues.containsKey(id)) {
            queue = new LinkedBlockingQueue<>();
            userQueues.put(id, queue);
        } else {
            queue = userQueues.get(id);
        }
        String message;
        try {
            message = queue.take();
            log.error(message);
            return ResponseEntity.ok(message);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Polling interrupted.");
        }
    }

    /*
    推送消息
     */
    @PostMapping("/send")
    public Result sendMessage(@RequestBody ChatMessage chatMessage) {
        try {
            //获取或创建代理服务器
            ProxyServer proxyServer = proxyServerManager.getOrCreateProxyServer(String.valueOf(chatMessage.getSenderId()),userQueues);
            String message = chatMessage.getSenderId() + "#" + chatMessage.getReceiverId() + "#" + chatMessage.getMessageContent() + "#" + chatMessage.getImageContent();
//            log.error("给tcp发消息:" + message);
            // 发送消息到 TCP 服务器
            proxyServer.sendMessage(message);
            return Result.success();
        } catch (Exception e) {
            System.out.println("Failed to send message to user " + chatMessage.getSenderId() + ": " + e.getMessage());
            return Result.error("失败");
        }
    }

    @GetMapping("/disconnect")
    public Result disconnect(@RequestParam String userId) {
        try {
            if (proxyServerManager.containsUserId(userId)) {
                proxyServerManager.disconnectProxyServer(userId);
                TcpServer.destroyClientWriter(userId);
                System.out.println("用户 " + userId + " 与代理服务器断开连接.");
                return Result.success();
            } else {
                System.out.println("未找到用户 " + userId + " 的连接信息.");
                return Result.error(userId);
            }
        } catch (Exception e) {
            System.out.println("断开用户 " + userId + " 连接失败: " + e.getMessage());
            return Result.error(userId);
        }
    }
}
